package com.cn.txx.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.txx.utils.Constants;
import com.cn.txx.utils.EmailSender;
import com.cn.txx.utils.RedisUtils;

@RequestMapping("/test")
@Controller
public class TestAction {

	@Resource
	private RedisUtils redisUtils;
	
	@ResponseBody
	@RequestMapping("/setMap")
	public boolean setMap(){
		Map<String, Object> map = new HashMap<>();
		map.put("name", "李四");
		map.put("age", 18);
		map.put("sex", "women");
		return redisUtils.hmset("user:002", map);
	}
	
	@ResponseBody
	@RequestMapping("/getMap")
	public Object getMap(){
		Object obj = redisUtils.hmget("user:002", "name");
		System.out.println(obj);
		return obj;
	}
	
	@ResponseBody
	@RequestMapping("/getYzm")
	public String getYzm(HttpSession session){
		Object attribute = session.getAttribute(Constants.LOGIN_YZM);
		if(StringUtils.isEmpty(attribute)){
			attribute = "null";
		}
		return attribute.toString();
	}
 
	@ResponseBody
	@RequestMapping("/sendemail.do")
	public int testSend(final HttpSession session) throws Exception {
	   try {
		    Object object  = session.getAttribute(Constants.LOGIN_YZM);
		    if(!StringUtils.isEmpty(object)){
		    	return -99;
		    }
			String sendFrom = "309450801@qq.com";
		    String[] sendTo = {"1243434698@qq.com"};
		    String subject = "欢迎您注册本网站!";
		    long yzm = Math.round(Math.random()*1000000+1);
		    StringBuilder htmlContent = new StringBuilder()
		        .append("<html>")
		        .append("<head>")
		        .append("<title>")
		        .append("欢迎您注册本网站!")
		        .append("</title>")
		        .append("</head>")
		        .append("<body>")
		        .append("您的注册验证码为：<br/>")
		        .append("<h1>"+yzm+"</h1>")
		        .append("如果不是您本人操作，请忽略本邮件！")
		        .append("</body>")
		        .append("</html>");
		    EmailSender.sendHtmlMessage(sendFrom, sendTo, subject, htmlContent.toString());
		    System.out.println("邮件发送成功.");
		    session.setAttribute(Constants.LOGIN_YZM, yzm);
		    
		    //5分钟后清除该验证码
		    new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(5*60000);
						session.removeAttribute(Constants.LOGIN_YZM);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
			}).start();
		    return 1;
	   } catch (Exception e) {
			e.printStackTrace();
			return 0;
	   }
	}
}
